import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { varRouter, resetRouter } from '@/router'

console.log(varRouter)
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  // console.log(store)
  // 有token
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        // await 修饰异步   同步进度条
        const userInfo = await store.dispatch('user/getUserInfo')
        console.log(userInfo.roles.menus)
        const filterRouter = varRouter.filter(item => {
          // console.log(item)
          // 过滤每一项  返回满足要求的
          return userInfo.roles.menus.some(obj => {
            return obj === item.name
          })
        })
        // 直接放行
        // console.log(filterRouter)
        // 添加动态路由规则
        router.addRoutes([
          ...filterRouter, // 不符合规则的进入404
          { path: '*', redirect: '/404', hidden: true }
        ])
        // 添加侧边栏菜单
        store.commit('user/setMenus', filterRouter)
        // 动态路由缺陷  需要添加to.path
        next(to.path)
        resetRouter()
      }
      next()
    }
    // 无token
  } else {
    if (whiteList.includes(to.path)) {
      next() // 直接放行
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})
